<?php
/**
 * @file americandefine.php
 * @author LinLin
 * @date 2016年3月28日 上午10:06:11
 * @brief 
 */

namespace haibao\cms\data\americandrama;

use haibao\cms\model\filter\americandrama\AmericanDefine as AmericanDefineFilter;
use haibao\cms\model\filter\americandrama\AmericanStars as AmericanStarsFilter;
use haibao\cms\model\filter\americandrama\AmericanTag as AmericanTagFilter;
use haibao\cms\model\filter\americandrama\AmericanRadio as AmericanRadioFilter;
use haibao\cms\model\filter\americandrama\AmericanCategory as AmericanCategoryFilter;
use haibao\cms\business\americandrama\AmericanDefine as AmericanDefineBusiness;
use haibao\frame\data\query\Condition as Condition;
use \haibao\cms\data\Tag as TagData;
use \haibao\cms\business\Tag as tagBusiness;
use haibao\frame\data\Model;

class AmericanDefine extends \haibao\cms\data\BaseMysql{

    public function __construct(){
        parent::__construct('\haibao\cms\model\data\americandrama\americandefine');
    }
    
    public function getAmericanDramaLists($query){
        return $this->getAll($query);
    }

    public function getAmericanIdByTagId($celebrityTagIdArr){
        $americanStr = preg_replace('/\d+/','%s',implode(',',$celebrityTagIdArr));
        $sql = 'select AmericanId from AmericanTag where TagId in ('.$americanStr.')';
        $result = $this->query($sql,$celebrityTagIdArr);
        $americanIdArr = array();
        while($row = $result->fetch_assoc()){
            $americanIdArr[] = $row['AmericanId'];
        }
        return $americanIdArr;
    }
    
    
    /**
     * 通过美剧ID更新美剧
     */
    public function updateAmericanInfo($americanIds){
        $sql = "update AmericanDefine set UpdateTime = '".date('Y-m-d H:i:s')."',Published = %s where Id in (".implode($americanIds, ',').")";
        $this->query($sql,array(\haibao\cms\model\data\americandrama\AmericanDefine::PUBLISHED_STATUS_ING));
    }

    public function getAmericanWeekPlayById($episodesId){
        $weekInfo = array();
        $sql = 'select a.Id,a.AmericanId,a.PlayDate,a.PlayEpisode,a.AmericanNameCH,a.AmericanNameEN,b.NameCH,b.NameEN from AmericanPlayWeek as a left join AmericanDefine as b on a.AmericanId = b.Id where a.Id = %s';
        $weekInfo = $this->query($sql,array($episodesId))->fetch_assoc();
        return $weekInfo;
    }
    
    
    /**
     * 获取本周周播表
     */
    public function getWeekPlayAutoData(){
       $sql = "select AmericanId,PlayDate,PlayEpisode,AmericanNameCH,AmericanNameEN from AmericanPlayWeek where PlayDate between %s and %s and AmericanId is null order by PlayDate desc";
       $sdefaultDate = date("Y-m-d");
       $first=1;
       $w=date('w',strtotime($sdefaultDate));
       $week_start=date('Y-m-d',strtotime("$sdefaultDate -".($w ? $w - $first : 6).' days'));
       $week_end=date('Y-m-d',strtotime("$week_start +6 days"));
       $result = $this->query($sql,array($week_start,$week_end));
       $autoWeekInfo = array();
       while($row = $result->fetch_assoc()){
           $autoWeekInfo[] = $row;
       }
       return $autoWeekInfo;
    }
    
    /**
     * 编辑周播信息
     */
    public function updateAmericanWeekPlayById($weekId,$americanId,$weekDate,$episodesNum){
        if($weekId){
            $sql = 'update AmericanPlayWeek set PlayDate = %s,PlayEpisode = %s where Id = %s';
            $this->query($sql,array($weekDate,$episodesNum,$weekId));
            $data = array('opreaType' => 2); 
        }else{
            $playWeekFilter = new \haibao\cms\model\data\americandrama\AmericanPlayWeek();
            $playWeekFilter->AmericanId = $americanId;
            $playWeekFilter->PlayDate = $weekDate;
            $playWeekFilter->PlayEpisode = $episodesNum;
            $this->add($playWeekFilter);
            $data = array(
                'weekId' => $playWeekFilter->Id,
                'americanId' => $playWeekFilter->AmericanId,
                'playDate' => $playWeekFilter->PlayDate,
                'playEpisode' =>$playWeekFilter->PlayEpisode,
                'opreaType' => 1
            );
        }
        return $data;
        
    }
    
    /**
     * 保存美剧信息
     */
    public function saveAmericanInfo($model,$articleTag,$americanRadio,$americanType,$mergeArr,$tagModel){
       $this->beginTranscation();
       try {
            if($model->Id){
                $this->save($model);
                $americanTagId = \haibao\cms\business\Tag::getTagIdByName($model->NameCH);
            }else {
                $this->add($model);
                $americanTagId = $this->addRelTag($model->Id,$tagModel);
            }
            $this->addAmerianProperty($model->Id);
            $this->addAmericanTag($model->Id,$articleTag,$americanTagId);
            $this->addAmericanRadio($model->Id,$americanRadio);
            $this->addAmericanCategory($model->Id,$americanType);
            $this->addAmericanStars($model->Id,$mergeArr);
            
        } catch (\Exception $e) {
            $this->rollback();
            throw $e;
        }
        $this->endTranscation();
    }
    
    /**
     * 添加美剧属性
     */
    public function addAmerianProperty($americanId){
        if(!$americanId){
            return false;
        }
        $existInfo =  $this->getAmericanPropertyById($americanId);
        if(!$existInfo){
            $americanModel = new \haibao\cms\model\data\americandrama\AmericanProperty();
            $americanModel->AmericanId = $americanId;
            $this->add($americanModel);
        }else{
            return false;
        }
        
    }
    
    public function getAmericanPropertyById($americanId){
       $sql = 'select AmericanId from AmericanProperty where AmericanId = %s';
       return $this->query($sql,array($americanId))->fetch_assoc();
    }
    
    /**
     * 添加标签
     */
    public function addRelTag($americanId,$tagModel){
        if(!$americanId){
            return false;
        }
        $tagModel->Url= '/meiju/'.$americanId.'/';
        $tagData = new TagData();
        $tagData->addTag($tagModel);
        return $tagModel->Id;
    }
    
    /**
     * 添加美剧标签
     */
    public function addAmericanTag($americanId,$articleTag,$americanTagId){
        if(!$americanId){
            return false;
        }
        $this->query('delete from `AmericanTag` where AmericanId = %s', array(
            $americanId
        ));
        if($americanTagId){
            if(!in_array($americanTagId,$articleTag)){
                array_push($articleTag,$americanTagId);
            }
        }
        if(isset($articleTag) && $articleTag[0]){
            $sql = 'insert into AmericanTag(AmericanId,TagId) values ';
            $arrSql = $arrValues = array();
            foreach($articleTag as $key=>$val){
                array_push($arrSql, '(%s,%s)');
                array_push($arrValues, $americanId);
                array_push($arrValues, $val);
            }
            if($arrSql && $arrValues){
                $sql .= implode(',', $arrSql);
                $this->query($sql, $arrValues);
            }
        }
    }
    
    /**
     * 添加美剧所属电台
     */
    public function addAmericanRadio($americanId,$americanRadio){
        if(!$americanId){
            return false;
        }
        $this->query('delete from `AmericanRadio` where AmericanId = %s', array(
            $americanId
        ));
        if(isset($americanRadio) && $americanRadio){
            $sql = 'insert into AmericanRadio(AmericanId,RadioId) values ';
            $arrSql = $arrValues = array();
            foreach($americanRadio as $key=>$val){
                array_push($arrSql, '(%s,%s)');
                array_push($arrValues, $americanId);
                array_push($arrValues, $val);
            }
            if($arrSql && $arrValues){
                $sql .= implode(',', $arrSql);
                $this->query($sql, $arrValues);
            }
        }
    }
    
    /**
     * 添加美剧所属剧目类别
     */
    public function addAmericanCategory($americanId,$americanType){
        if(!$americanId){
            return false;
        }
        $this->query('delete from `AmericanCategory` where AmericanId = %s', array(
            $americanId
        ));
        if(isset($americanType) && $americanType){
            $sql = 'insert into AmericanCategory(AmericanId,CategoryId) values ';
            $arrSql = $arrValues = array();
            foreach($americanType as $key=>$val){
                array_push($arrSql, '(%s,%s)');
                array_push($arrValues, $americanId);
                array_push($arrValues, $val);
            }
            if($arrSql && $arrValues){
                $sql .= implode(',', $arrSql);
                $this->query($sql, $arrValues);
            }
        }
    }
    
    /**
     * 添加美剧关联的导演 演员信息
     */
    public function addAmericanStars($americanId,$mergeArr){
        if(!$americanId){
            return false;
        }
        $this->query('delete from `AmericanStars` where AmericanId = %s', array(
            $americanId
        ));
        if(isset($mergeArr) && $mergeArr){
            foreach($mergeArr as $key=>$val){
                $val->AmericanId = $americanId;
            }
            $this->addAll($mergeArr);
        }
    }
    
    /**
     * 删除美剧
     */
    public function changeAmericanStatus($americanId,$status){
       $this->query('update AmericanDefine set Status=%s where Id=%s limit 1', array(
		    $status, $americanId
		));
    }
    
    
    /**
     * 删除美剧周播
     */
    public function delAmericanWeekPlay($weekId){
        $this->query('delete from AmericanPlayWeek where Id=%s limit 1', array(
            $weekId
        ));
    }
    
    public function getAmericanDefineByName($name){
    	return $this->query('select Id from AmericanDefine where NameCH=%s limit 1', array(
    			$name
    	))->fetch_assoc();
    }
    
    /**
     * 添加周播剧集信息
     */
    public function addWeekInfo($americanPlayWeekModel){
        if($americanPlayWeekModel->Id){
            $this->save($americanPlayWeekModel);
        }else{
            $this->add($americanPlayWeekModel);
        }
    }

    public function getTvStarByStarTagIds($starTagIds){
        $stars = array();
        if($starTagIds) {
            $str = preg_replace('/(\d+)/', '%s', implode(',', $starTagIds));
            $sql = 'select TagId from AmericanStars where TagId in (' . $str . ') and TagType = 1';
            $result = $this->query($sql, $starTagIds);
            while ($result->fetch_assoc()) {
                $stars[] = $result->getData('TagId');
            }
        }
        return $stars;
    }

    public function getRecDrama($cateIds,$dramaId){
        $statusOk = \haibao\cms\model\data\americandrama\AmericanDefine::STATUS_ENABLE;
        $Published = \haibao\cms\model\data\americandrama\AmericanDefine::PUBLISHED_STATUS_ENABLE;
        $str = preg_replace('/(\d+)/', '%s', implode(',', $cateIds));
        $sql = 'select distinct(ad.Id),ad.NameCH,ad.AvatarUrl from AmericanDefine as ad left join AmericanCategory ac
                on ad.Id = ac.AmericanId
                where ad.Published = '.$Published.' and ad.Status = '.$statusOk.' and  ac.CategoryId in ('.$str.')
                and ad.Id <> '.$dramaId.'
                order by ad.UpdateTime desc limit 6';
        $result = $this->query($sql,$cateIds);
        $resArr = array();
        if($result){
            while($result->fetch_assoc()){
                $resArr[$result->getData('Id')]['NameCH'] = $result->getData('NameCH');
                $resArr[$result->getData('Id')]['Avatar'] = $result->getData('AvatarUrl');
            }
        }
        return $resArr;
    }

    public function updatePublishStatus($americanId,$status){
        $sql = "update AmericanDefine set Published = %s where Id = %s";
        $this->query($sql,array($status,$americanId));
    }
    

    public function updateCommentNum($americanId,$num = 1,$isSub=false){
    	if ($isSub){
    		$sql = 'update AmericanProperty set CommentNum=CommentNum-'.$num.' where AmericanId=%s';
    	}else {
    		$sql = 'update AmericanProperty set CommentNum=CommentNum+'.$num.' where AmericanId=%s';
    	}
    	$this->query($sql,array($americanId));
    }
    
    public function getAmericanProperty($arrIds){
        $arrIds = (array)$arrIds;
        $americanPropertyArr = array();
        $str = preg_replace('/\d+/', '%s', implode(',',$arrIds));
        $result = $this->query("select AmericanId,ClickNum,CommentNum,CommentPariseNum,QuestionNum,QuestionPariseNum from AmericanProperty where AmericanId in ($str)", $arrIds);
        while ($result->fetch_assoc()){
            $temp = array();
            $temp['commentNum'] = $result->getData('CommentNum')+$result->getData('CommentPariseNum')+$result->getData('QuestionNum')+$result->getData('QuestionPariseNum');
            $temp['clickNum'] = $result->getData('ClickNum');
            $americanPropertyArr[$result->getData('AmericanId')] = $temp;
        }
        return $americanPropertyArr;
    }
}